﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MyFinanceManager.Objects;

namespace MyFinanceManager.PC
{
    /// <summary>
    /// Interaction logic for ucViewCategoriesTree.xaml
    /// </summary>
    public partial class ucViewCategoriesTree : UserControl
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ucViewCategoriesTree"/> class.
        /// </summary>
        public ucViewCategoriesTree()
        {
            InitializeComponent();
            Refresh();
        }

        #region Methods
        /// <summary>
        /// Refreshes this instance.
        /// </summary>
        internal void Refresh()
        {
            this.tvEarnings.Items.Clear();
            this.tvExpenses.Items.Clear();

            if (RepositoryCenter.Repositoy.EarningsCategorized != null)
            {
                AddNodes(RepositoryCenter.Repositoy.EarningsCategorized, this.tvEarnings.Items, +1);
                this.tbEarnings.Content = RepositoryCenter.Repositoy.EarningsCategorized.SaldoKumuliert.ToString("C");
            }
            if (RepositoryCenter.Repositoy.ExpensesCategorized != null)
            {
                AddNodes(RepositoryCenter.Repositoy.ExpensesCategorized, this.tvExpenses.Items, -1);
                this.tbExpenses.Content = (RepositoryCenter.Repositoy.ExpensesCategorized.SaldoKumuliert * -1).ToString("C");
            }
            this.tbSaldo.Content = (RepositoryCenter.Repositoy.EarningsCategorized.SaldoKumuliert - RepositoryCenter.Repositoy.ExpensesCategorized.SaldoKumuliert).ToString("C");
        }

        /// <summary>
        /// Adds all nodes of one category to a TreeViewCollection 
        /// </summary>
        /// <param name="catItem">The cat item.</param>
        /// <param name="itemCollection">The item collection.</param>
        /// <param name="faktor">The faktor.</param>
        private void AddNodes(CatItem catItem, ItemCollection itemCollection, int faktor)
        {
            foreach (var item in catItem)
            {
                TreeViewItem tvi = new TreeViewItem();

                tvi.Header = String.Format("{0} ({1:C})", item.Name, item.SaldoKumuliert * faktor);
                itemCollection.Add(tvi);

                if (item.HasChildren)
                {
                    AddNodes(item, tvi.Items, faktor);
                }
            }
        }

        #endregion
    }
}
